//
//  CZBindBankController.m
//  TCProject
//
//  Created by admin on 16/2/1.
//  Copyright © 2016年 wise-wing. All rights reserved.
//

#import "CZBindBankController.h"
#import "AccountManager.h"
#import "CAlertView.h"
#import "CheckBankCard.h"
#import "BankCardBin.h"


@interface CZBindBankController ()<UITextFieldDelegate>
/**
 *  服务器返回的安全码
 */
@property (nonatomic, copy) NSString *sureCode;
@property (nonatomic, copy) NSString *secureCode;

@property (nonatomic, strong) CAlertView *alertView;
@property (nonatomic, strong) BankCardBin *bankBin;
@property (weak, nonatomic) IBOutlet UITextField *nameTextField;
@property (weak, nonatomic) IBOutlet UITextField *bankNoTextField;
- (IBAction)bindAction:(id)sender;

@property (weak, nonatomic) IBOutlet UITextField *secureCodeTextfield;

- (IBAction)cancleAlertAction:(id)sender;
- (IBAction)okAlertAction:(id)sender;

@end

@implementation CZBindBankController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.rowHeight = 44.f;
    self.bankBin = [BankCardBin new];
    
    [self getData];
}

- (void)getData
{
    BMRequest *request = [BMRequest requestWithPath:@"checkOwnerSureCodeIsNull.htm"];
    request.params = @{@"id": @([AccountManager sharedInstance].user.ID)};
    [self showHudWithhint:kDefaultMessage];
    [[BMHttpTool sharedInstance] postWith:request finish:^(BMResponse *response, NSError *error) {
        [self hideHud];
        if (response.status == kResultOK) {
            self.sureCode = response.rawResult[@"sureCode"];
        } else {
            [self showHint:@"获取安全码失败"];
        }
    }];
}

- (CAlertView *)alertView
{
    if (!_alertView) {
        _alertView = [[CAlertView alloc] init];
    }
    return _alertView;
}

- (IBAction)bindAction:(id)sender {
    [self.view endEditing:YES];
    
    NSString *name = _nameTextField.text;
    if ([BMUtils isEmptyString:name]) {
        [self showHint:@"持卡人姓名不能为空"];
        return;
    }
    
    NSString *bankNo = [_bankNoTextField.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    if (![CheckBankCard checkBankCard:bankNo]) {
        [self showHint:@"不是有效的银行卡号"];
        return;
    };
    
    NSString *fullName = [self.bankBin getNameOfBank:[bankNo substringWithRange:NSMakeRange(0, 6)] offset:0];
    NSRange range = [fullName rangeOfString:@" "];
    
    if (range.location == NSNotFound) {
        [self showHint:@"未知的卡类型"];
        return;
    }
    
    if ([BMUtils isEmptyString:_sureCode]) {
        UIView *alert = [[NSBundle mainBundle] loadNibNamed:@"SecureCodeAlertView" owner:self options:nil].firstObject;
        alert.layer.cornerRadius = 5.f;
        self.alertView.contentView = alert;
        [self.alertView show];
        return;
    } else if ([BMUtils isEmptyString:_secureCode]) {
        UIView *alert = [[NSBundle mainBundle] loadNibNamed:@"InputSecureCodeView" owner:self options:nil].firstObject;
        alert.layer.cornerRadius = 5.f;
        self.alertView.contentView = alert;
        [self.alertView show];
    }
}

- (void)bindTask
{
    [self.view endEditing:YES];
    
    NSString *name = _nameTextField.text;
    if ([BMUtils isEmptyString:name]) {
        [self showHint:@"持卡人姓名不能为空"];
        return;
    }
    
    NSString *bankNo = [_bankNoTextField.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    if (![CheckBankCard checkBankCard:bankNo]) {
        [self showHint:@"不是有效的银行卡号"];
        return;
    };
    
    NSString *fullName = [self.bankBin getNameOfBank:[bankNo substringWithRange:NSMakeRange(0, 6)] offset:0];
    NSRange range = [fullName rangeOfString:@" "];
    
    if (range.location == NSNotFound) {
        [self showHint:@"未知的卡类型"];
        return;
    }
    
    NSString *bankName = [fullName substringToIndex:range.location];
    NSString *bankType = [fullName substringFromIndex:range.location + range.length];
    
    BMRequest *request = [BMRequest requestWithPath:@"bank/add.htm"];
    NSDictionary *dict = @{@"bankName": bankName, @"bankType": bankType, @"bankNum": bankNo, @"cardHolder": name, @"ownerId": @([AccountManager sharedInstance].user.ID)};
    
    if (self.secureCode) {
        NSMutableDictionary *params = [NSMutableDictionary dictionaryWithDictionary:dict];
        params[@"sureCode"] = self.secureCode;
        request.params = params;
    } else {
        request.params = dict;
    }
    
    [self showHudWithhint:kDefaultMessage];
    [[BMHttpTool sharedInstance] postWith:request finish:^(BMResponse *response, NSError *error) {
        [self hideHud];
        if (response.status == kResultOK) {
            [self.navigationController popViewControllerAnimated:YES];
        } else {
            [self showHint:@"绑定银行卡失败!"];
        }
    }];
}

- (IBAction)cancleAlertAction:(id)sender {
    [self.alertView dismissAlertViewWithAnimated:YES];
}

- (IBAction)okAlertAction:(id)sender {
    NSString *code = _secureCodeTextfield.text;
    if (code.length < 6 || code.length > 16) {
        [self showHint:@"请输入6-16位安全码"];
        return;
    }
    [self.alertView dismissAlertViewWithAnimated:YES];
    
    if ([BMUtils isEmptyString:_sureCode]) {
        self.secureCode = code;
        [self bindTask];
    } else {
        [self checkSecureCodeTask];
    }
}

- (void)checkSecureCodeTask
{
    BMRequest *requeset = [BMRequest requestWithPath:@"checkSureCode.htm"];
    requeset.params = @{@"id": @([AccountManager sharedInstance].user.ID), @"sureCode": _secureCodeTextfield.text};
    [self showHudWithhint:kDefaultMessage];
    [[BMHttpTool sharedInstance] postWith:requeset finish:^(BMResponse *response, NSError *error) {
        [self hideHud];
        if (response.status == kResultOK) {
            self.secureCode = self.sureCode;
            [self bindTask];
        } else {
            [self showHint:response.msg];
        }
    }];
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSString *text = textField.text;
    
    NSCharacterSet *characterSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789\b"];
    string = [string stringByReplacingOccurrencesOfString:@" " withString:@""];
    if ([string rangeOfCharacterFromSet:[characterSet invertedSet]].location != NSNotFound) {
        return NO;
    }
    
    text = [text stringByReplacingCharactersInRange:range withString:string];
    text = [text stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    NSString *newString = @"";
    while (text.length > 0) {
        NSString *subString = [text substringToIndex:MIN(text.length, 4)];
        newString = [newString stringByAppendingString:subString];
        if (subString.length == 4) {
            newString = [newString stringByAppendingString:@" "];
        }
        text = [text substringFromIndex:MIN(text.length, 4)];
    }
    
    newString = [newString stringByTrimmingCharactersInSet:[characterSet invertedSet]];
    
    if (newString.length >= 24) {
        return NO;
    }
    
    [textField setText:newString];
    
    if (textField.text.length > 6) {
        NSString *newStr = [textField.text stringByReplacingOccurrencesOfString:@" " withString:@""];
        NSString *bankName = [self.bankBin getNameOfBank:[newStr substringWithRange:NSMakeRange(0, 6)] offset:0];
        UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:0]];
        cell.detailTextLabel.text = bankName;
    }
    
    return NO;
}

@end
